<template>
  <Modal
    ref="uploadModal"
    v-model="modal"
    title="导入决策流"
    @on-ok="handleOk"
    @on-cancel="handleCancel"
    :closable="false"
    :mask-closable="false"
  >
    <Upload
      ref="uploadComponent"
      :data="{param: 'asdasd'}"
      type="drag"
      action="//jsonplaceholder.typicode.com/posts/"
      :max-size="10 * 1024"
      accept="xml"
      :format="['xml']"
      :before-upload="handleBeforeUpload"
      :on-success="handleUploadSuccess"
      :on-remove="handleUploadRemove"
    >
      <div style="padding: 100px 0">
        <Icon type="ios-cloud-upload" size="52" style="color: #3399ff" />
        <p>将文件拖拽至此处或点击上传</p>
      </div>
    </Upload>
    <p style="text-align: center">仅支持上传.xml文件，且文件数量最多为1个，文件大小不超过10MB</p>
  </Modal>
</template>

<script>
export default {
  data () {
    return {
      modal: false,
      uploadList: [],
      xmlStr: ''
    }
  },
  methods: {
    show () {
      this.modal = true
    },
    // 上传文件之前处理
    handleBeforeUpload (file) {
      // 读取文件内容
      const reader = new FileReader()
      reader.onload = (e) => {
        this.xmlStr = e.target.result || ''
      }
      // 参数只能是File或者Blob对象
      reader.readAsText(file)
      const fileLength = this.$refs.uploadComponent.fileList.length + 1
      if (file.type !== 'text/xml') {
        this.$Message.warning('上传文件必须为xml格式')
        return false
      }
      if (file.size > 10 * 1024 * 1024) {
        this.$Message.warning('上传文件大小不得超过10MB')
        return false
      }
      if (fileLength > 1) {
        this.$Message.warning('上传文件数量最多为1个')
        return false
      }
      return true
    },
    resetUpload () {
      this.$refs.uploadComponent.fileList = []
      this.uploadList = []
      this.modal = false
    },
    handleOk () {
      // 导入之后进行显示视图
      this.$Message.success('导入成功')
      this.$emit('on-import-xml', this.xmlStr)
      this.resetUpload()
    },
    handleCancel () {
      // 重置数据
      this.resetUpload()
    },
    updateFileList (file, fileList) {
      if (file.status === 'finished') {
        this.uploadList = fileList.map(ele => {
          return {
            name: ele.name,
            url: ele.url || '',
            uid: ele.uid
          }
        })
      }
    },
    handleUploadSuccess (res, file, fileList) {
      this.updateFileList(file, fileList)
    },
    handleUploadRemove (file, fileList) {
      this.updateFileList(file, fileList)
    }
  }
}
</script>

<style scoped>
</style>
